<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="公司名称" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入公司名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="银行卡号" prop="bankAccount">
        <el-input
          v-model="queryParams.bankAccount"
          placeholder="请输入银行卡号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="法人姓名" prop="legalName">
        <el-input
          v-model="queryParams.legalName"
          placeholder="请输入法人姓名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="legalPhone">
        <el-input
          v-model="queryParams.legalPhone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="城市列表" prop="cityList">
        <el-input
          v-model="queryParams.cityList"
          placeholder="请输入城市列表"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="认证通过时间" prop="authTime">
        <el-date-picker
          v-model="queryParams.authTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['weiyi:user-auth:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['weiyi:user-auth:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table 
      v-loading="loading" 
      :data="list" 
      :stripe="true" 
      :show-overflow-tooltip="true"
      style="width: 100%"
      border
    >
      <el-table-column label="ID" align="center" prop="id" width="60" />
      <el-table-column label="用户ID" align="center" prop="userId" width="80" />
      <el-table-column label="公司名称" align="center" prop="companyName" min-width="120" />
      <el-table-column label="法人信息" align="center" width="120">
        <template #default="{ row }">
          <div>{{ row.legalName }}</div>
          <div class="text-gray-500 text-sm">{{ row.legalPhone }}</div>
        </template>
      </el-table-column>
      <el-table-column label="数据类型" align="center" min-width="120">
        <template #default="{ row }">
          <div v-if="row.dataType">
            <el-tag 
              v-for="type in parseDataTypeList(row.dataType)" 
              :key="type.value" 
              class="mr-1 mb-1"
              :type="getDataTypeTagType(type.value)"
            >
              {{ type.label }}
            </el-tag>
          </div>
          <span v-else class="text-gray-400">未设置</span>
        </template>
      </el-table-column>
      <el-table-column label="认证状态" align="center" prop="status" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
        </template>
      </el-table-column>
      
      <!-- 添加数据接收状态切换 -->
      <el-table-column label="数据接收状态" align="center" width="120">
        <template #default="{ row }">
          <el-switch
            v-model="row.dataReceiveStatus"
            :active-value="1"
            :inactive-value="0"
            @change="handleDataReceiveStatusChange(row)"
            :disabled="row.status !== 1"
          />
        </template>
      </el-table-column>
      
      <el-table-column label="价格类型" align="center" prop="priceType" width="100">
        <template #default="{ row }">
          <el-tag :type="row.priceType === 1 ? 'success' : 'warning'">
            {{ row.priceType === 1 ? '固定单价' : row.priceType === 2 ? '浮动单价' : '未设置' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="价格信息" align="center" width="120">
        <template #default="{ row }">
          <div v-if="row.priceType === 1">
            <span class="font-bold">{{ row.fixedPrice }}</span> 元/条
          </div>
          <div v-else-if="row.priceType === 2">
            <span class="font-bold">{{ row.minPrice }}</span> - 
            <span class="font-bold">{{ row.maxPrice }}</span> 元/条
          </div>
          <div v-else>未设置</div>
        </template>
      </el-table-column>
      <el-table-column label="每日限制" align="center" prop="dailyDataLimit" width="100">
        <template #default="{ row }">
          <el-tag type="info">
            {{ row.dailyDataLimit ? row.dailyDataLimit + ' 条' : '无限制' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180"
      />
      <el-table-column
        label="认证时间"
        align="center"
        prop="authTime"
        :formatter="dateFormatter"
        width="180"
      />
      <el-table-column label="操作" align="center" width="180" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['weiyi:auth:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['weiyi:auth:delete']"
          >
            删除
          </el-button>
          <el-button
            v-if="scope.row.status === 0"
            link
            type="success"
            @click="openApproveDialog(scope.row)"
            v-hasPermi="['weiyi:auth:update']"
          >
            审批
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <UserAuthForm ref="formRef" @success="getList" />
  
  <!-- 审批弹窗 -->
  <el-dialog
    v-model="approveDialogVisible"
    title="企业认证审批"
    width="600px"
    destroy-on-close
  >
    <div v-if="currentAuth" v-loading="detailLoading">
      <el-tabs>
        <el-tab-pane label="基本信息">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="公司名称" :span="2">{{ currentAuth.companyName }}</el-descriptions-item>
            <el-descriptions-item label="法人姓名">{{ currentAuth.legalName }}</el-descriptions-item>
            <el-descriptions-item label="法人手机号">{{ currentAuth.legalPhone }}</el-descriptions-item>
            
            <!-- 银行信息 -->
            <el-descriptions-item label="开户行" :span="2">
              {{ currentAuth.bankName || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="开户名称" :span="2">
              {{ currentAuth.bankAccountName || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="银行账号" :span="2">
              {{ currentAuth.bankAccount || '未设置' }}
            </el-descriptions-item>
            
            <!-- 价格信息 -->
            <el-descriptions-item label="每日数据限制">{{ currentAuth.dailyDataLimit || '无限制' }}</el-descriptions-item>
            <el-descriptions-item label="价格类型">
              {{ currentAuth.priceType === 1 ? '固定单价' : currentAuth.priceType === 2 ? '浮动单价' : '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item v-if="currentAuth.priceType === 1" label="固定单价">
              {{ currentAuth.fixedPrice }} 元/条
            </el-descriptions-item>
            <el-descriptions-item v-if="currentAuth.priceType === 2" label="浮动单价范围" :span="2">
              {{ currentAuth.minPrice }} - {{ currentAuth.maxPrice }} 元/条
            </el-descriptions-item>
            
            <!-- 添加数据类型显示 -->
            <el-descriptions-item label="数据类型" :span="2" v-if="currentAuth.dataType">
              <el-tag 
                v-for="type in parseDataTypeList(currentAuth.dataType)" 
                :key="type.value" 
                class="mr-1 mb-1"
                :type="getDataTypeTagType(type.value)"
              >
                {{ type.label }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
        <el-tab-pane label="证件信息">
          <div class="grid grid-cols-1 gap-4">
            <div>
              <div class="mb-2 font-bold">营业执照</div>
              <el-image
                v-if="currentAuth.businessLicense"
                :src="currentAuth.businessLicense"
                :preview-src-list="[currentAuth.businessLicense]"
                fit="contain"
                style="width: 100%; max-height: 200px"
              />
              <div v-else class="text-gray-400">未上传</div>
            </div>
            <div class="grid grid-cols-2 gap-4">
              <div>
                <div class="mb-2 font-bold">身份证正面</div>
                <el-image
                  v-if="currentAuth.legalIdFront"
                  :src="currentAuth.legalIdFront"
                  :preview-src-list="[currentAuth.legalIdFront]"
                  fit="contain"
                  style="width: 100%; max-height: 150px"
                />
                <div v-else class="text-gray-400">未上传</div>
              </div>
              <div>
                <div class="mb-2 font-bold">身份证背面</div>
                <el-image
                  v-if="currentAuth.legalIdBack"
                  :src="currentAuth.legalIdBack"
                  :preview-src-list="[currentAuth.legalIdBack]"
                  fit="contain"
                  style="width: 100%; max-height: 150px"
                />
                <div v-else class="text-gray-400">未上传</div>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="城市与数据类型" v-if="currentAuth.cityList || currentAuth.dataTypeList">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="城市列表" v-if="currentAuth.cityList">
              <el-tag 
                v-for="city in parseCityList(currentAuth.cityList)" 
                :key="city" 
                class="mr-1 mb-1"
              >
                {{ city }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="数据类型" v-if="currentAuth.dataTypeList">
              <el-tag 
                v-for="type in parseDataTypeList(currentAuth.dataTypeList)" 
                :key="type.value" 
                class="mr-1 mb-1"
                :type="getDataTypeTagType(type.value)"
              >
                {{ type.label }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
      </el-tabs>
      
      <el-divider />
      
      <el-form :model="approveForm" label-width="100px" class="mt-4">
        <el-form-item label="价格类型" required>
          <el-radio-group v-model="approveForm.priceType">
            <el-radio :label="1">固定单价</el-radio>
            <el-radio :label="2">浮动单价</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item v-if="approveForm.priceType === 1" label="固定单价" required>
          <el-input-number 
            v-model="approveForm.fixedPrice" 
            :precision="2" 
            :step="0.1" 
            :min="0"
            placeholder="请输入固定单价（元/条）"
            class="!w-full"
          />
        </el-form-item>
        
        <el-form-item v-if="approveForm.priceType === 2" label="浮动单价下限" required>
          <el-input-number 
            v-model="approveForm.minPrice" 
            :precision="2" 
            :step="0.1" 
            :min="0"
            placeholder="请输入浮动单价下限（元/条）"
            class="!w-full"
          />
        </el-form-item>
        
        <el-form-item v-if="approveForm.priceType === 2" label="浮动单价上限" required>
          <el-input-number 
            v-model="approveForm.maxPrice" 
            :precision="2" 
            :step="0.1" 
            :min="0"
            placeholder="请输入浮动单价上限（元/条）"
            class="!w-full"
          />
        </el-form-item>
        
        <el-form-item label="每日数据限制" required>
          <el-input-number 
            v-model="approveForm.dailyDataLimit" 
            :min="0" 
            :step="10"
            placeholder="请输入每日数据提取限制（0表示无限制）"
            class="!w-full"
          />
        </el-form-item>
        
        <!-- 城市选择 -->
        <el-form-item label="城市选择" required>
          <el-select
            v-model="approveForm.cityList"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择或输入城市/省份"
            class="!w-full"
            :loading="loadingAreas"
          >
            <el-option-group label="省份/自治区/直辖市">
              <el-option 
                v-for="province in provinces" 
                :key="province.value" 
                :label="province.label" 
                :value="province.value" 
              />
            </el-option-group>
            <el-option-group label="城市">
              <el-option 
                v-for="city in cities" 
                :key="city.value" 
                :label="city.label" 
                :value="city.value" 
              />
            </el-option-group>
          </el-select>
          <div class="text-gray-500 text-sm mt-1">
            <Icon icon="ep:info-filled" class="mr-1" />
            可以选择省份或城市，也可以直接输入城市名称，支持多选
          </div>
        </el-form-item>
        
        <!-- 数据类型选择 -->
        <el-form-item label="数据类型" required>
          <el-checkbox-group v-model="approveForm.dataTypeList" class="w-full">
            <el-checkbox :label="1">车抵贷</el-checkbox>
            <el-checkbox :label="2">信贷</el-checkbox>
            <el-checkbox :label="3">公积金</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        
        <el-divider>审批结果</el-divider>
        
        <el-form-item label="审批结果" required>
          <el-radio-group v-model="approveForm.status">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审批备注">
          <el-input
            v-model="approveForm.auditRemark"
            type="textarea"
            :rows="3"
            placeholder="请输入审批备注"
          />
        </el-form-item>
        
        <!-- 驳回原因，仅当选择拒绝时显示 -->
        <el-form-item v-if="approveForm.status === 2" label="驳回原因" required>
          <el-input
            v-model="approveForm.rejectReason"
            type="textarea"
            :rows="3"
            placeholder="请输入驳回原因，将会返回给用户"
          />
          <div class="text-gray-500 text-sm mt-1">
            <Icon icon="ep:info-filled" class="mr-1" />
            驳回原因将直接返回给用户，请详细说明需要修改的内容
          </div>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button @click="approveDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleApprove" :loading="approveLoading">确认</el-button>
    </template>
  </el-dialog>
  
  <!-- 图片预览 -->
  <el-image-viewer
    v-if="imageViewerVisible"
    :url-list="previewImages"
    :initial-index="previewIndex"
    @close="imageViewerVisible = false"
  />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { UserAuthApi, UserAuthVO } from '@/api/weiyi/userauth'
import { updateDataReceiveConfigStatus } from '@/api/weiyi/data'
import UserAuthForm from './UserAuthForm.vue'
import { Picture } from '@element-plus/icons-vue'
import { ElImageViewer } from 'element-plus'
import { getAreaTree } from '@/api/system/area'

/** 用户认证信息 列表 */
defineOptions({ name: 'UserAuth' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<UserAuthVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  userId: undefined,
  companyName: undefined,
  businessLicense: undefined,
  bankAccount: undefined,
  legalName: undefined,
  legalIdFront: undefined,
  legalIdBack: undefined,
  legalPhone: undefined,
  status: undefined,
  auditRemark: undefined,
  priceType: undefined,
  fixedPrice: undefined,
  minPrice: undefined,
  maxPrice: undefined,
  dailyDataLimit: undefined,
  cityList: undefined,
  dataType: undefined,
  dataTypeList: undefined,
  createTime: [],
  authTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

// 审批相关
const approveDialogVisible = ref(false)
const currentAuth = ref<any>(null)
const approveForm = reactive({
  id: 0,
  status: 1, // 默认通过
  auditRemark: '',
  rejectReason: '', // 驳回原因
  priceType: 1,
  fixedPrice: 0,
  minPrice: 0,
  maxPrice: 0,
  dailyDataLimit: 0,
  cityList: [] as string[], // 城市列表
  dataTypeList: [] as number[] // 数据类型列表
})
const approveLoading = ref(false)
const detailLoading = ref(false)

// 图片预览相关
const imageViewerVisible = ref(false)
const previewImages = ref<string[]>([])
const previewIndex = ref(0)

// 省份和城市数据
const provinces = ref<any[]>([])
const cities = ref<any[]>([])
const loadingAreas = ref(false)

// 加载省市数据
const loadAreaData = async () => {
  loadingAreas.value = true
  try {
    const res = await getAreaTree()
    if (res) {
      // 省份数据
      provinces.value = res.map(province => ({
        label: province.name,
        value: province.name,
        children: province.children || []
      }))
      
      // 城市数据
      const cityList: any[] = []
      provinces.value.forEach(province => {
        if (province.children && province.children.length > 0) {
          province.children.forEach((city: any) => {
            cityList.push({
              label: city.name,
              value: city.name,
              provinceId: province.id,
              provinceName: province.name
            })
          })
        }
      })
      cities.value = cityList
    }
  } catch (error) {
    console.error('获取地区数据失败:', error)
    message.error('获取地区数据失败')
  } finally {
    loadingAreas.value = false
  }
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await UserAuthApi.getUserAuthPage(queryParams)
    // 为数据添加默认的数据接收状态字段，默认为0（关闭）
    list.value = data.list.map(item => ({
      ...item,
      dataReceiveStatus: item.dataReceiveStatus ?? 0
    }))
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await UserAuthApi.deleteUserAuth(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await UserAuthApi.exportUserAuth(queryParams)
    download.excel(data, '用户认证信息.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

// 打开审批弹窗
const openApproveDialog = async (row: UserAuthVO) => {
  approveDialogVisible.value = true
  detailLoading.value = true
  
  try {
    // 获取详细信息
    const detail = await UserAuthApi.getUserAuth(row.id)
    currentAuth.value = detail
    
    // 初始化表单
    approveForm.id = detail.id
    approveForm.status = 1 // 默认通过
    approveForm.auditRemark = ''
    approveForm.rejectReason = '' // 重置驳回原因
    
    // 初始化价格相关字段
    approveForm.priceType = detail.priceType || 1
    approveForm.fixedPrice = detail.fixedPrice || 0
    approveForm.minPrice = detail.minPrice || 0
    approveForm.maxPrice = detail.maxPrice || 0
    approveForm.dailyDataLimit = detail.dailyDataLimit || 0
    
    // 初始化城市列表
    approveForm.cityList = parseCityList(detail.cityList || '[]')
    
    // 初始化数据类型列表
    // 优先使用dataType字段，如果不存在则使用dataTypeList字段
    const dataTypeSource = detail.dataType || detail.dataTypeList || '[]'
    const dataTypes = parseDataTypeList(dataTypeSource)
    approveForm.dataTypeList = dataTypes.map(item => typeof item === 'object' ? item.value : item)
  } catch (error) {
    console.error('获取详情失败:', error)
    message.error('获取详情失败')
  } finally {
    detailLoading.value = false
  }
}

// 解析城市列表
const parseCityList = (cityListStr: string) => {
  try {
    return JSON.parse(cityListStr)
  } catch (e) {
    return []
  }
}

// 解析数据类型列表
const parseDataTypeList = (dataTypeListStr: string) => {
  try {
    const types = JSON.parse(dataTypeListStr)
    // 如果是简单数组，转换为对象数组
    if (Array.isArray(types) && (typeof types[0] === 'number' || typeof types[0] === 'string')) {
      return types.map(value => {
        return {
          value,
          label: getDataTypeLabel(value)
        }
      })
    }
    return types
  } catch (e) {
    return []
  }
}

// 获取数据类型标签
const getDataTypeLabel = (type: number | string) => {
  const typeMap = {
    '1': '车抵贷',
    '2': '信用贷',
    '3': '公积金',
    '4': '企业贷',
    '5': '消费贷'
  }
  return typeMap[type] || `类型${type}`
}

// 获取数据类型标签样式
const getDataTypeTagType = (type: number | string) => {
  const typeMap = {
    '1': 'success',
    '2': 'primary',
    '3': 'warning',
    '4': 'danger',
    '5': 'info'
  }
  return typeMap[type] || ''
}

// 处理审批
const handleApprove = async () => {
  try {
    approveLoading.value = true
    
    // 确保当前认证对象存在
    if (!currentAuth.value) {
      message.error('认证信息不存在')
      return
    }
    
    // 如果是拒绝状态，且没有填写驳回原因，提示错误
    if (approveForm.status === 2 && !approveForm.rejectReason.trim()) {
      message.error('请填写驳回原因')
      approveLoading.value = false
      return
    }
    
    // 如果是拒绝状态，调用驳回接口
    if (approveForm.status === 2) {
      // 构建驳回数据，包含所有字段
      const rejectData: any = {
        id: approveForm.id,
        rejectReason: approveForm.rejectReason,
        // 保留原有字段
        userId: currentAuth.value.userId,
        companyName: currentAuth.value.companyName,
        businessLicense: currentAuth.value.businessLicense,
        legalName: currentAuth.value.legalName,
        legalIdFront: currentAuth.value.legalIdFront,
        legalIdBack: currentAuth.value.legalIdBack,
        legalPhone: currentAuth.value.legalPhone,
        cityList: JSON.stringify(approveForm.cityList),
        dataType: JSON.stringify(approveForm.dataTypeList), // 使用审批表单中的数据类型
        dataTypeList: JSON.stringify(approveForm.dataTypeList),
        
        // 银行信息（保持原样）
        bankName: currentAuth.value.bankName,
        bankAccountName: currentAuth.value.bankAccountName,
        bankAccount: currentAuth.value.bankAccount,
        
        // 价格相关字段
        priceType: approveForm.priceType,
        dailyDataLimit: approveForm.dailyDataLimit
      }
      
      // 根据价格类型设置价格字段
      if (approveForm.priceType === 1) {
        rejectData.fixedPrice = approveForm.fixedPrice
        // 清空浮动价格字段
        rejectData.minPrice = 0
        rejectData.maxPrice = 0
      } else if (approveForm.priceType === 2) {
        // 清空固定价格字段
        rejectData.fixedPrice = 0
        // 设置浮动价格字段
        rejectData.minPrice = approveForm.minPrice
        rejectData.maxPrice = approveForm.maxPrice
      }
      
      await UserAuthApi.rejectAuth(rejectData)
      message.success('驳回成功')
      approveDialogVisible.value = false
      // 刷新列表
      await getList()
      approveLoading.value = false
      return
    }
    
    // 构建审批数据，包含所有字段
    const approveData: any = {
      // 保留原有字段
      id: approveForm.id,
      userId: currentAuth.value.userId,
      companyName: currentAuth.value.companyName,
      businessLicense: currentAuth.value.businessLicense,
      legalName: currentAuth.value.legalName,
      legalIdFront: currentAuth.value.legalIdFront,
      legalIdBack: currentAuth.value.legalIdBack,
      legalPhone: currentAuth.value.legalPhone,
      cityList: JSON.stringify(approveForm.cityList),
      dataType: JSON.stringify(approveForm.dataTypeList), // 使用审批表单中的数据类型
      dataTypeList: JSON.stringify(approveForm.dataTypeList),
      
      // 银行信息（保持原样）
      bankName: currentAuth.value.bankName,
      bankAccountName: currentAuth.value.bankAccountName,
      bankAccount: currentAuth.value.bankAccount,
      
      // 更新的字段
      status: approveForm.status,
      auditRemark: approveForm.auditRemark,
      priceType: approveForm.priceType,
      dailyDataLimit: approveForm.dailyDataLimit
    };
    
    // 根据价格类型设置价格字段
    if (approveForm.priceType === 1) {
      approveData.fixedPrice = approveForm.fixedPrice
      // 清空浮动价格字段
      approveData.minPrice = 0
      approveData.maxPrice = 0
    } else if (approveForm.priceType === 2) {
      // 清空固定价格字段
      approveData.fixedPrice = 0
      // 设置浮动价格字段
      approveData.minPrice = approveForm.minPrice
      approveData.maxPrice = approveForm.maxPrice
    }
    
    // 如果是审批通过，设置认证时间为当前时间
    if (approveForm.status === 1) {
      approveData.authTime = new Date().getTime()
    }
    
    await UserAuthApi.approveAuth(approveData)
    message.success(approveForm.status === 1 ? '审批通过成功' : '审批拒绝成功')
    approveDialogVisible.value = false
    // 刷新列表
    await getList()
  } catch (error) {
    console.error('审批失败:', error)
    message.error('审批失败')
  } finally {
    approveLoading.value = false
  }
}

// 获取状态类型
const getStatusType = (status: number) => {
  switch (status) {
    case 0: return 'warning' // 待审核
    case 1: return 'success' // 已认证
    case 2: return 'danger'  // 未通过
    default: return 'info'
  }
}

// 获取状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case 0: return '待审核'
    case 1: return '已认证'
    case 2: return '未通过'
    default: return '未知'
  }
}

// 预览图片
const previewImage = (url: string) => {
  previewImages.value = [url]
  previewIndex.value = 0
  imageViewerVisible.value = true
}

/** 初始化 **/
onMounted(() => {
  getList()
  loadAreaData() // 加载省市数据
})

// 处理数据接收状态变更
const handleDataReceiveStatusChange = async (row: any) => {
  try {
    const status = row.dataReceiveStatus
    await updateDataReceiveConfigStatus({
      id: row.id,
      status: status
    })
    message.success(status === 1 ? '数据接收已开启' : '数据接收已关闭')
  } catch (error) {
    console.error('更新数据接收状态失败:', error)
    // 恢复原状态
    row.dataReceiveStatus = row.dataReceiveStatus === 1 ? 0 : 1
    message.error('更新数据接收状态失败')
  }
}
</script>

<style lang="scss" scoped>
.image-error {
  display: flex;
  width: 100%;
  height: 100%;
  font-size: 20px;
  color: #909399;
  background-color: #f5f7fa;
  justify-content: center;
  align-items: center;
}

.cursor-pointer {
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    transform: scale(1.05);
  }
}

.text-xs {
  font-size: 12px;
}
</style>